<template>

    <el-form :model="form" ref="formModel">
        <el-form-item
            label="购买数量"
            prop="goumaishuliang"
            required
            :rules="[{required:true, message:'请填写购买数量'}, {validator:rule.checkNumber, message:'输入一个有效数字'}, {validator:rule.checkMin, value:1}]">
            <el-input type="number" placeholder="输入购买数量" style="width: 450px" v-model.number="form.goumaishuliang" />
        </el-form-item>

        <el-form-item v-if="btnText">


            <template v-if="$session.cx == '用户'">
            <el-button  v-if="form.faburen != $session.username" type="primary" @click="submit">加入购物车</el-button>
            <el-button v-if="form.faburen != $session.username"  type="primary" @click="addOrder">立即购买</el-button>
            </template>

        </el-form-item>
    </el-form>

</template>

<script setup>
    import http from "@/utils/ajax/http";
    import DB from "@/utils/db";
    import rule from "@/utils/rule";
    import router from "@/router";

    import { ref, reactive, computed } from "vue";
    import { useRoute } from "vue-router";
    import { session } from "@/utils/utils";
    import { ElMessage, ElMessageBox } from "element-plus";
    import { useGouwucheCreateForm, canGouwucheInsert } from "@/module";

    const route = useRoute();
    const props = defineProps({
        id: [String, Number],
        btnText: {
            type: String,
            default: "保存",
        },
        isRead: {
            type: Boolean,
            default: true,
        },
        isHouxu: {
            type: Boolean,
            default: true,
        },
    });
    const { form, readMap } = useGouwucheCreateForm(props.id);
    const emit = defineEmits(["success"]);
    const formModel = ref();
    const loading = ref(false);
    var submit = () => {
        formModel.value.validate().then((res) => {
            if (loading.value) return;
            loading.value = true;
            canGouwucheInsert(form).then(
                (res) => {
                    loading.value = false;
                    if (res.code == 0) {
                        emit("success", res.data);
                        if (props.isHouxu) {
                            ElMessage.success("添加成功");
                            router.go(-1);
                        }
                    } else {
                        ElMessageBox.alert(res.msg);
                    }
                },
                (err) => {
                    loading.value = false;
                    ElMessageBox.alert(err.message);
                }
            );
        });
    };

    function addOrder() {
        formModel.value.validate().then((res) => {
            var shangpin = JSON.stringify(form);
            router.push({path:'/shangpindingdan/add',query:{shangpin:shangpin}});
        });

    }

</script>

<style scoped lang="scss">
    .views-gouwuche-web-add {
    }
</style>
